package com.peach.inquiry;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.peach.inquiry.imsdk.TimManager;
import com.peach.inquiry.imsdk.LogUtil;
import com.peach.inquiry.imsdk.thread.ThreadPools;
import com.peach.inquiry.imsdk.tim.ITimUserStatusListener;
import com.peach.inquiry.imsdk.tim.conversation.ConversationBean;
import com.peach.inquiry.imsdk.tim.conversation.IConversationListener;
import com.peach.inquiry.imsdk.tim.message.IMsgListener;
import com.peach.inquiry.imsdk.tim.message.MsgBean;
import com.peach.inquiry.imsdk.tim.message.MsgUtil;
import com.tencent.imsdk.v2.V2TIMDownloadCallback;
import com.tencent.imsdk.v2.V2TIMElem;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSoundElem;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;


public class IM {

    public static class BaseLopper extends Handler {

        private BaseLopper(Looper looper) {
            super(looper);
        }

        private static BaseLopper instance;

        public static BaseLopper getInstance() {
            if (instance == null) {
                synchronized (IM.class) {
                    if (instance == null) {
                        instance = new BaseLopper(Looper.getMainLooper());
                    }
                }
            }

            return instance;
        }

        public void runOnUiThread(Runnable runnable) {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                runnable.run();
            } else {
                post(runnable);
            }
        }

    }

    public static Context staticContext;
    public static Activity staticActivity;

    public static Gson gson = new Gson();

    /**
     * 语音消息msgID-url，异步获取语音消息url
     */
    public static Map<String, V2TIMSoundElem> SoundElemListByMsgIDMap = new HashMap<>();


    /**
     * 获取语音消息url
     *
     * @param msgID
     */
    public void getSoundPath(final String msgID) {
        final V2TIMSoundElem soundElem = SoundElemListByMsgIDMap.get(msgID);
        final String soundPath = staticContext.getCacheDir() + File.separator + soundElem.getUUID();
        File soundFile = new File(soundPath);
        if (soundFile.exists()) {
            if (soundFile.length() > 10) {
                if (methodChannel != null) {
                    HashMap<String, Object> args = new HashMap<>();
                    args.put("msgID", msgID);
                    args.put("path", soundPath);
                    args.put("duration", soundElem.getDuration());
                    methodChannel.invokeMethod("refreshSoundPath", gson.toJson(args));
                }
            }
        } else {
            soundElem.downloadSound(soundPath, new V2TIMDownloadCallback() {
                @Override
                public void onProgress(V2TIMElem.V2ProgressInfo v2ProgressInfo) {

                }

                @Override
                public void onError(int i, String s) {

                }

                @Override
                public void onSuccess() {
                    if (methodChannel != null) {
                        HashMap<String, Object> args = new HashMap<>();
                        args.put("msgID", msgID);
                        args.put("path", soundPath);
                        args.put("duration", soundElem.getDuration());
                        methodChannel.invokeMethod("refreshSoundPath", gson.toJson(args));
                    }
                }
            });
        }

    }


    MethodChannel methodChannel;

    IConversationListener mConversationCallback;

    public IM(Context context, Activity activity, MethodChannel channel) {
        staticContext = context.getApplicationContext();
        staticActivity = activity;
        methodChannel = channel;


        mConversationCallback = new IConversationListener() {
            @Override
            public void refresh(ArrayList<ConversationBean> conversationBeans) {
                LogUtil.e("刷新会话列表", conversationBeans.size() + "");
                if (methodChannel != null) {
                    String jsonList = new Gson().toJson(conversationBeans);
                    LogUtil.e("刷新会话列表", jsonList);
                    methodChannel.invokeMethod("refChatList", jsonList);
                }
            }

            @Override
            public void setNextSeq(long nextSeq) {
                LogUtil.e("设置会话列表setNextSeq  ", nextSeq + "");
                if (methodChannel != null) {
                    methodChannel.invokeMethod("setChatListNextSeq", nextSeq + "");
                }
            }
        };

        TimManager.getInstance().setConversationListener(mConversationCallback);

        TimManager.getInstance().initConversationListener();
        TimManager.getInstance().initAdvancedMsgListener();
        TimManager.getInstance().setUserStatusListener(new ITimUserStatusListener() {
            @Override
            public void onUserLoginListener(int status, String errorStr) {
                boolean isSuccess = status == V2TIMManager.V2TIM_STATUS_LOGINED;
                if (isSuccess) {
                    IM.this.afterLoginSuccess();
                } else {
                    IM.this.userStatus(status);
                }
            }

            @Override
            public void onUserStatus(int status) {
                IM.this.userStatus(status);
            }

            @Override
            public void onConnectStatus(int status) {
                /**
                 * 连接状态
                 * 0：连接成功，非0连接失败
                 */
                IM.this.onConnectStatus(status);
            }
        });
    }

    public void  initSdk(int timAppID){
        TimManager.getInstance().initTIM(timAppID);
    }


    public void setActivity(Activity a) {
        staticActivity = a;
    }


    /**
     * 成功登录
     */
    public void afterLoginSuccess() {

        LogUtil.e("用户为已登录状态");

        methodChannel.invokeMethod("loginSuccess", null);

        TimManager.getInstance().setMsgListener(new IMsgListener() {
            @Override
            public void newMsg(V2TIMMessage v2TIMMessage) {
                LogUtil.e("新消息 " + gson.toJson(v2TIMMessage));
                MsgBean msg = MsgUtil.V2TIMMessage2MessageBean(v2TIMMessage);
//                insert2UserIDMsgListMap(v2TIMMessage.getUserID(), v2TIMMessage);
                methodChannel.invokeMethod("newMsg", gson.toJson(msg));
            }

            @Override
            public void refreshChatUI(List<V2TIMMessage> v2TIMMessageList) {
                LogUtil.e("消息列表 ");
                if (v2TIMMessageList == null) {
                    methodChannel.invokeMethod("refreshChatUIEmpty", null);
                } else {
                    LogUtil.e("消息列表 " + v2TIMMessageList.size());
                    if (!v2TIMMessageList.isEmpty()) {
                        //todo  2020-11-06 13:43:01.801 7407-7407/com.example.example E/tim-tim-: 获取单聊历史消息 返回缓存  224
                        //2020-11-06 13:43:48.166 7407-7407/com.example.example E/tim-tim-: 获取单聊历史消息 返回缓存  448
                        //2020-11-06 13:43:57.835 7407-7407/com.example.example E/tim-tim-: 获取单聊历史消息 返回缓存  896
                        //2020-11-06 13:44:37.164 7407-7407/com.example.example E/tim-tim-: 获取单聊历史消息 返回缓存  1792
//                        add2UserIDMsgListMap(v2TIMMessageList.get(0).getUserID(), v2TIMMessageList);

                    }

                    List<MsgBean> msgBeanList = MsgUtil.V2TIMMessageList2MessageBeanList(v2TIMMessageList);
//                    LogUtil.e("消息列表 转 自定义 " + gson.toJson(msgBeanList));
                    methodChannel.invokeMethod("refreshChatUI", gson.toJson(msgBeanList));
                }
            }

            @Override
            public void sendProgress(String msgID, int progress) {
                LogUtil.e("消息发送进度 " + msgID + "   progress  " + progress);
                HashMap<String, Object> args = new HashMap<>();
                args.put("msgID", msgID);
                args.put("progress", progress);
                methodChannel.invokeMethod("sendProgress", gson.toJson(args));
            }

            @Override
            public void sendFailed(String msgID, String des) {
                LogUtil.e("消息发送失败 " + msgID + "   des  " + des);
                HashMap<String, Object> args = new HashMap<>();
                args.put("msgID", msgID);
                args.put("des", des);
                methodChannel.invokeMethod("sendFailed", gson.toJson(args));
            }
        });
    }

    /***
     * 用户在线状态
     */
    public void userStatus(int status) {
        LogUtil.e("用户状态 " + status);
        if (status == V2TIMManager.V2TIM_STATUS_LOGOUT) {
            TimManager.getInstance().logout();
            TimManager.getInstance().removeAdvancedMsgListener();
        }
        if (status == V2TIMManager.V2TIM_STATUS_LOGINED) {
            this.afterLoginSuccess();
        }
    }

    /**
     * 连接状态
     *
     * @param status 0：连接成功，非0连接失败
     */
    public void onConnectStatus(int status) {
        LogUtil.e("连接状态,0：连接成功，非0连接失败-- " + status);
    }
}
